
#include "connection.h"
#include <vector>
#include <boost\bind.hpp>
#include "connection_manage.h"
#include "log.h"


namespace jump{
	namespace server{

		Connection::Connection(boost::asio::io_service& arg_ioService,Connection_Manage& arg_conn_manage)
			:socket_(arg_ioService),
			connectionManage_(arg_conn_manage)
		{
			//strncpy(buf_,"MSG_TRANSFER\r\n",MAX_LENGTH);
		}

		void Connection::start()
		{
			socket_.async_read_some(boost::asio::buffer(buf_,MAX_LENGTH),
				boost::bind(&Connection::handle_read,this,
				boost::asio::placeholders::error));
		}

		boost::asio::ip::tcp::socket& Connection::socket()
		{
			return socket_;
		}
		void Connection::stop()
		{
			socket_.close();
		}

		void Connection::handle_write(const boost::system::error_code& arg_ec)
		{
			if(!arg_ec)
			{
				//LOG_INFO("WROTE");
				socket_.async_read_some(boost::asio::buffer(buf_,MAX_LENGTH),
					boost::bind(&Connection::handle_read,shared_from_this(),
					boost::asio::placeholders::error));

			}
			else if(arg_ec!=boost::asio::error::operation_aborted)
			{
				LOG_ERR("Error When handle Write:",arg_ec.message());
				connectionManage_.stop(shared_from_this());
			}
		}

		void Connection::handle_read(const boost::system::error_code& arg_ec)
		{
			if(!arg_ec)
			{

				//LOG_INFO(buf_);

				//with sendBuf_.data() ,
				//data in sendBuf_ will not clear out after async_write operation end
				boost::asio::async_write(socket_,boost::asio::buffer(buf_,MAX_LENGTH),
					boost::bind(&Connection::handle_write,shared_from_this(),
					boost::asio::placeholders::error));

			}else if(arg_ec!=boost::asio::error::operation_aborted)
			{
				LOG_ERR("Error When handle Read:",arg_ec.message());
				connectionManage_.stop(shared_from_this());

			}

			//keep on read

			//shared_from_this(),
			//if pointer to current instance comes to here without save,
			//it will disappear as sonn as current function ended.
			//and instance it self will disappear along with the only pointer.

			//but with shared_from_this(), referrence couting of current instance will grow with one,
			//so when the function ended, instance won't disappear.

		}

	}

}